<template>
  <div class="discovery">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>设备发现</span>
          <el-button 
            v-if="!discovering"
            type="primary" 
            @click="startDiscovery"
          >
            开始发现
          </el-button>
          <el-button 
            v-else
            type="danger" 
            @click="stopDiscovery"
          >
            停止发现
          </el-button>
        </div>
      </template>
      
      <div class="discovery-config">
        <el-form :model="discoveryForm" label-width="120px" inline>
          <el-form-item label="发现方式">
            <el-radio-group v-model="discoveryForm.method">
              <el-radio label="auto">自动发现</el-radio>
              <el-radio label="range">IP范围</el-radio>
              <el-radio label="manual">手动添加</el-radio>
            </el-radio-group>
          </el-form-item>
          
          <el-form-item label="IP范围" v-if="discoveryForm.method === 'range'">
            <el-input v-model="discoveryForm.startIp" placeholder="起始IP" style="width: 150px" />
            <span style="margin: 0 10px">-</span>
            <el-input v-model="discoveryForm.endIp" placeholder="结束IP" style="width: 150px" />
          </el-form-item>
          
          <el-form-item label="设备IP" v-if="discoveryForm.method === 'manual'">
            <el-input v-model="discoveryForm.manualIp" placeholder="192.168.1.100" style="width: 200px" />
          </el-form-item>
          
          <el-form-item label="超时时间">
            <el-input-number v-model="discoveryForm.timeout" :min="1" :max="60" style="width: 120px" />
            <span style="margin-left: 5px">秒</span>
          </el-form-item>
        </el-form>
      </div>
      
      <div class="discovery-progress" v-if="discovering">
        <el-progress :percentage="discoveryProgress" :status="discoveryStatus" />
        <p class="progress-text">{{ discoveryStatusText }}</p>
      </div>
      
      <div class="discovered-devices">
        <h3>发现的设备 ({{ discoveredDevices.length }})</h3>
        <el-table :data="discoveredDevices" v-loading="discovering">
          <el-table-column type="selection" width="55" />
          <el-table-column prop="name" label="设备名称" min-width="180" />
          <el-table-column prop="ip" label="IP地址" width="140" />
          <el-table-column prop="manufacturer" label="厂商" width="100" />
          <el-table-column prop="model" label="型号" width="120" />
          <el-table-column prop="deviceType" label="设备类型" width="100" />
          <el-table-column prop="onvifPort" label="ONVIF端口" width="100" />
          <el-table-column prop="location" label="位置" width="100" />
          <el-table-column prop="discoveryTime" label="发现时间" width="150" />
          <el-table-column prop="status" label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="getStatusType(row.status)">{{ row.status }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200">
            <template #default="{ row }">
              <el-button size="small" @click="testConnection(row)" :loading="row.testing">
                测试连接
              </el-button>
              <el-button size="small" type="primary" @click="addDevice(row)" :disabled="row.status !== '在线'">
                添加设备
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <div class="batch-actions" v-if="discoveredDevices.length > 0">
          <el-button @click="selectAll">全选</el-button>
          <el-button @click="clearSelection">清空选择</el-button>
          <el-button type="primary" @click="batchAdd">批量添加</el-button>
          <el-button @click="exportResults">导出结果</el-button>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { discoverDevices, addDiscoveredDevice, scanIpRange, validateDevice, getScanStatus, stopScan } from '@/api/discovery'
import { useDeviceStore } from '@/stores/device'

const deviceStore = useDeviceStore()
const discovering = ref(false)
const discoveryProgress = ref(0)
const discoveryStatus = ref('')
const discoveryStatusText = ref('')
const scanTimer = ref(null)

const discoveryForm = reactive({
  method: 'auto',
  startIp: '192.168.1.1',
  endIp: '192.168.1.254',
  manualIp: '',
  timeout: 10
})

const discoveredDevices = ref([])

const startDiscovery = async () => {
  discovering.value = true
  discoveryProgress.value = 0
  discoveryStatus.value = ''
  discoveredDevices.value = []
  
  try {
    discoveryStatusText.value = '正在初始化设备发现...'
    
    let response
    
    if (discoveryForm.method === 'auto') {
      // 自动发现ONVIF设备
      discoveryStatusText.value = '正在搜索ONVIF设备...'
      response = await discoverDevices()
    } else if (discoveryForm.method === 'range') {
      // IP范围扫描
      if (!discoveryForm.startIp || !discoveryForm.endIp) {
        ElMessage.error('请输入有效的IP范围')
        return
      }
      
      discoveryStatusText.value = `正在扫描IP范围 ${discoveryForm.startIp} - ${discoveryForm.endIp}...`
      
      const scanConfig = {
        startIp: discoveryForm.startIp,
        endIp: discoveryForm.endIp,
        port: 80,
        timeout: discoveryForm.timeout,
        threads: 10
      }
      
      // 启动扫描
      await scanIpRange(scanConfig)
      
      // 轮询扫描状态
      await pollScanStatus()
      return
    } else if (discoveryForm.method === 'manual') {
      // 手动添加单个设备
      if (!discoveryForm.manualIp) {
        ElMessage.error('请输入设备IP地址')
        return
      }
      
      discoveryStatusText.value = `正在验证设备 ${discoveryForm.manualIp}...`
      
      const deviceInfo = {
        ipAddress: discoveryForm.manualIp,
        port: 80,
        username: 'admin',
        password: 'admin'
      }
      
      response = await validateDevice(deviceInfo)
    }
    
    // 处理发现结果
    if (response && response.data && response.data.data) {
      const devices = Array.isArray(response.data.data) ? response.data.data : [response.data.data]
      
      discoveredDevices.value = devices.map(device => ({
        id: device.endpointReference || Date.now() + Math.random(),
        name: device.manufacturer && device.model ? `${device.manufacturer} ${device.model}` : (device.manufacturer || device.model || `设备 ${device.ipAddress}`),
        ip: device.ipAddress,
        manufacturer: device.manufacturer || 'Unknown',
        model: device.model || device.deviceType || 'Unknown',
        onvifPort: device.onvifPort || 80,
        status: '已发现',
        testing: false,
        location: device.location || '',
        discoveryTime: device.discoveryTime || '',
        deviceType: device.deviceType || 'Unknown',
        rawData: device
      }))
      
      discoveryStatus.value = 'success'
      discoveryStatusText.value = `发现完成，找到 ${discoveredDevices.value.length} 个设备`
      ElMessage.success(`发现完成，找到 ${discoveredDevices.value.length} 个设备`)
    } else {
      discoveryStatus.value = 'success'
      discoveryStatusText.value = '发现完成，未找到设备'
      ElMessage.info('发现完成，未发现任何设备')
    }
  } catch (error) {
    console.error('设备发现失败:', error)
    discoveryStatus.value = 'exception'
    discoveryStatusText.value = '设备发现失败'
    ElMessage.error(`设备发现失败: ${error.message || '未知错误'}`)
  } finally {
    discovering.value = false
    if (scanTimer.value) {
      clearInterval(scanTimer.value)
      scanTimer.value = null
    }
  }
}

const pollScanStatus = async () => {
  return new Promise((resolve, reject) => {
    scanTimer.value = setInterval(async () => {
      try {
        const statusResponse = await getScanStatus()
        const status = statusResponse.data.data || statusResponse.data
        
        discoveryProgress.value = status.progress || 0
        discoveryStatusText.value = status.message || '正在扫描...'
        
        if (status.completed) {
          clearInterval(scanTimer.value)
          scanTimer.value = null
          
          // 获取扫描结果
          if (status.devices && status.devices.length > 0) {
            discoveredDevices.value = status.devices.map(device => ({
              id: device.endpointReference || Date.now() + Math.random(),
              name: device.manufacturer && device.model ? `${device.manufacturer} ${device.model}` : (device.manufacturer || device.model || `设备 ${device.ipAddress}`),
              ip: device.ipAddress,
              manufacturer: device.manufacturer || 'Unknown',
              model: device.model || device.deviceType || 'Unknown',
              onvifPort: device.onvifPort || 80,
              status: '已发现',
              testing: false,
              location: device.location || '',
              discoveryTime: device.discoveryTime || '',
              deviceType: device.deviceType || 'Unknown',
              rawData: device
            }))
            
            discoveryStatus.value = 'success'
            discoveryStatusText.value = `扫描完成，找到 ${discoveredDevices.value.length} 个设备`
            ElMessage.success(`扫描完成，找到 ${discoveredDevices.value.length} 个设备`)
          } else {
            discoveryStatus.value = 'success'
            discoveryStatusText.value = '扫描完成，未找到设备'
            ElMessage.info('扫描完成，未发现任何设备')
          }
          
          resolve()
        } else if (status.error) {
          clearInterval(scanTimer.value)
          scanTimer.value = null
          discoveryStatus.value = 'exception'
          discoveryStatusText.value = '扫描过程中出现错误'
          ElMessage.error(`扫描失败: ${status.error}`)
          reject(new Error(status.error))
        }
      } catch (error) {
        clearInterval(scanTimer.value)
        scanTimer.value = null
        discoveryStatus.value = 'exception'
        discoveryStatusText.value = '获取扫描状态失败'
        ElMessage.error(`获取扫描状态失败: ${error.message}`)
        reject(error)
      }
    }, 1000) // 每秒轮询一次
  })
}

// 测试连接
const testConnection = async (device) => {
  device.testing = true
  
  try {
    const deviceInfo = {
      ipAddress: device.ip,
      port: device.onvifPort || 80,
      username: 'admin',
      password: 'admin'
    }
    
    const response = await validateDevice(deviceInfo)
    
    if (response.data && response.data.status === 'ONLINE') {
      device.status = '在线'
      ElMessage.success(`设备 ${device.ip} 连接测试成功`)
    } else {
      device.status = '离线'
      ElMessage.warning(`设备 ${device.ip} 连接测试失败`)
    }
  } catch (error) {
    console.error('连接测试失败:', error)
    device.status = '离线'
    ElMessage.error(`设备 ${device.ip} 连接测试失败: ${error.message || '未知错误'}`)
  } finally {
    device.testing = false
  }
}

const addDevice = async (device) => {
  try {
    const deviceData = {
      name: device.name,
      ipAddress: device.ip,
      port: device.onvifPort || 80,
      manufacturer: device.manufacturer,
      model: device.model,
      username: 'admin',
      password: 'admin',
      description: `通过发现添加的${device.manufacturer} ${device.model}设备`
    }
    
    const response = await addDiscoveredDevice(deviceData)
    
    if (response.data) {
      // 添加到设备存储
      await deviceStore.fetchDevices()
      ElMessage.success(`设备 ${device.name} 添加成功`)
      
      // 从发现列表中移除已添加的设备
      const index = discoveredDevices.value.findIndex(d => d.id === device.id)
      if (index > -1) {
        discoveredDevices.value.splice(index, 1)
      }
    } else {
      ElMessage.error(`设备 ${device.name} 添加失败`)
    }
  } catch (error) {
    console.error('添加设备失败:', error)
    ElMessage.error(`设备 ${device.name} 添加失败: ${error.message || '未知错误'}`)
  }
}

const selectAll = () => {
  // TODO: 实现全选逻辑
  ElMessage.info('全选功能待实现')
}

const clearSelection = () => {
  // TODO: 实现清空选择逻辑
  ElMessage.info('清空选择功能待实现')
}

const batchAdd = () => {
  // TODO: 实现批量添加逻辑
  ElMessage.info('批量添加功能待实现')
}

// 停止发现
const stopDiscovery = async () => {
  try {
    if (scanTimer.value) {
      clearInterval(scanTimer.value)
      scanTimer.value = null
    }
    
    // 调用后端停止扫描API
    await stopScan()
    
    discovering.value = false
    discoveryStatus.value = 'stopped'
    discoveryStatusText.value = '发现已停止'
    ElMessage.info('设备发现已停止')
  } catch (error) {
    console.error('停止发现失败:', error)
    ElMessage.error(`停止发现失败: ${error.message || '未知错误'}`)
  }
}

const exportResults = () => {
  // TODO: 实现导出功能
  ElMessage.info('导出功能待实现')
}

const getStatusType = (status) => {
  switch (status) {
    case '在线':
      return 'success'
    case '离线':
      return 'danger'
    case '已发现':
      return 'warning'
    case '未知':
      return 'info'
    default:
      return 'info'
  }
}
</script>

<style scoped>
.discovery {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.discovery-config {
  margin-bottom: 20px;
  padding: 15px;
  background: var(--el-bg-color-page);
  border-radius: 8px;
}

.discovery-progress {
  margin: 20px 0;
}

.progress-text {
  text-align: center;
  margin-top: 10px;
  color: var(--el-text-color-regular);
}

.discovered-devices h3 {
  margin-bottom: 15px;
}

.batch-actions {
  margin-top: 15px;
  text-align: center;
}

.batch-actions .el-button {
  margin: 0 5px;
}
</style>